"use strict"

const uuid = require("uuid")
const BaseController = require("./base")
class BookController extends BaseController {
  //获取所有图书信息
  async index() {
    const { ctx, service } = this;
    const { pageNum, pageSize, ...where } = ctx.query;
    const result = await service.book.list(
      isNaN(pageNum) ? 1 : parseInt(pageNum),
      isNaN(pageSize) ? 3 : parseInt(pageSize),
      where
    );
    if (result) {
      this.Success({ result, msg: '获取成功' });
    } else {
      this.Error('获取失败');
    }
  }
  //获取单条图书信息
  async single() {
    const { ctx, service } = this;
    const id = ctx.params.id;
    const result = await service.book.single(id);
    //console.log(result)
    if (result) {
      this.Success({result, msg:"获取成功"})
    } else {
      this.Error("获取失败")
    }
  }
  //创建图书
  async create() {
    const { ctx, service } = this;
    const book = ctx.request.body
    //查询数据库是否存在相同内容
    const isExists = await service.book.isExist(book.title)
    if (isExists.length > 0) {
      this.Error("该书籍已存在")
    } else {
      book.bookId = uuid.v4();
      book.create_time = Date.now();
      let categoryId = book.category_id;
      const result = await service.book.create(book, categoryId);
      if (result.affectedRows === 1) {
        this.Success(result, "新增成功");
      } else {
        this.Error("新增失败");
      }
    }
  }
  //修改图书
  async update() {
    const { ctx, service } = this;
    const id = ctx.params.id;
    const book = ctx.request.body;
    book.id = id;
    book.update_time = Date.now();
    const result = await service.book.update(book);
    if (result.affectedRows === 1) {
      this.Success(result, "修改成功");
    } else {
      this.Error("修改失败");
    }
  }

  //删除图书
  async destroy() {
    const { ctx, service } = this
    const id = ctx.params.id
    //console.log(id)
    const result = await service.book.destroy(id)
    if (result.affectedRows === 1) {
      this.Success(result, "删除成功")
    } else {
      this.Error("删除失败")
    }
  }

  //修改图书的分类
  async editBookCategory() {
    const { ctx, service } = this
    const categoryinfo = ctx.request.body
    console.log(categoryinfo)
    const result = await service.book.editCateGory(categoryinfo)
    console.log(result)
    if (result.affectedRows === 1) {
      this.Success(result, "修改成功")
    } else {
      this.Error("修改失败")
    }
  }
}

module.exports = BookController
